/*
 * @Author: xiaosihan 
 * @Date: 2023-04-18 15:18:19 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2025-08-26 18:31:50
 */

import Taro from "@tarojs/taro";
import { get } from "lodash";
import userStore from "src/pages/User/userStore";
import utils from "src/utils/utils";

// 请求的基类
export default class Api {

    constructor() { }

    static ossRoot = "//static.uniqtee.com";
    static ossDirectory = "ugc-img";

    //访问域名
    baseURL = "https://gateway.uniqtee.com/utApp";

    //开发模式访问的域名
    // devBaseURL = "http://192.168.1.54:9060/utApp";
    // devBaseURL = "http://47.97.40.88:9066/utApp";
    devBaseURL = "https://gateway.uniqtee.com/utApp";

    // devBaseURL = "http://47.111.138.202:7080/utApp";
    // devBaseURL = "http://60.182.78.200:7080/utApp";

    //超时时间
    timeout = 10000;

    // 带凭据
    withCredentials = false;

    // get请求
    async _get(url: string, params?: {}, trynum = 0): Promise<any> {
        const baseURL = utils.isDev ? this.devBaseURL : this.baseURL;
        try {
            const res = await Taro.request({
                url: `${baseURL}${url}`,
                method: "GET",
                data: params,
                header: url === "/wx/getToken" ? {} :
                    {
                        authorization: `Bearer ${Taro.getStorageSync('token')}`
                    },
                timeout: this.timeout,
            });
            return this._handleResponse(res);
        } catch (err) {
            if (trynum < 3) {
                return this._get(url, params, trynum + 1);
            } else {
                console.log(`${baseURL}${url}`);
                return this._handleError(err);
            }
        }
    }

    // post 请求
    async _post(url: string, data = {}, trynum = 0): Promise<any> {
        const baseURL = utils.isDev ? this.devBaseURL : this.baseURL;
        try {
            const res = await Taro.request({
                url: `${baseURL}${url}`,
                method: "POST",
                data,
                header: {
                    authorization: `Bearer ${Taro.getStorageSync('token')}`
                },
                timeout: this.timeout,
            });
            return this._handleResponse(res);
        } catch (err) {
            if (trynum < 3) {
                return this._post(url, data, trynum + 1);
            } else {
                console.log(`${baseURL}${url}`);
                return this._handleError(err);
            }
        }
    }
    // from 请求
    async _from(url: string, data = {}): Promise<any> {
        const baseURL = utils.isDev ? this.devBaseURL : this.baseURL;

        try {
            const res = await Taro.request({
                url: `${baseURL}${url}`,
                method: "POST",
                data,
                header: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    authorization: `Bearer ${Taro.getStorageSync('token')}`
                },
                timeout: this.timeout,
            });
            return this._handleResponse(res);
        } catch (err) {
            console.log(`${baseURL}${url}`);
            return this._handleError(err);
        }
    }

    // 上传
    // async _upload(url: string, file: any): Promise<any> {
    //     const { baseURL, headers } = this._createInstance();
    //     try {
    //         const res = await Taro.uploadFile({
    //             url: `${baseURL}${url}`,
    //             filePath: file.path,
    //             name: file.name,
    //             header: headers,
    //         });
    //         return this._handleResponse(res);
    //     } catch (err) {
    //         return this._handleError(err);
    //     }
    // }

    // 处理响应
    _handleResponse(res: Taro.request.SuccessCallbackResult<any>): any {
        const code = get(res, ['data', 'code']);
        const msg = get(res, ['data', 'msg'], "--");
        if ([401, 402].includes(code)) {
            Taro.removeStorageSync('token');
            userStore.setIsLogin(false);
        } else if ([500].includes(code)) {
            //判断 msg 里面有 申请失败字样就不提示
            if (msg.indexOf("申请失败") === -1) {
                Taro.showToast({ title: msg, icon: 'none' });
            }
        }
        return res.data;
    }

    // 处理错误
    _handleError(err: any): any {
        const code = get(err, ['response', 'data', 'code']);
        if ([401, 402].includes(code)) {
            Taro.removeStorageSync('token');
            userStore.setIsLogin(false);
        } else {
            console.log(get(err, ['response', 'data', 'message']) || '请求失败');
            // Taro.showToast({ title: get(err, ['response', 'data', 'message']) || '请求失败', icon: 'none' });
        }
        return Promise.reject(err);
    }
}
